<%@ page pageEncoding="utf-8"%>
<%!
	//查询所有的健康标准及其子标准
	Message queryHealth(Input input) {
		Message msg = new Message(0);
		Integer hospital = input.getInt("hospital");
		Integer type = input.getInt("type", -9999);
		String content = "new map(id as id, name as name, defaultUnit as default_unit, commonUnits as common_units)";
		Where where = new Where("hospital=", hospital).and("status=", STATUS_ENABLE).and("parent=", -1);
		if (type != -9999) {
			where.and("type=", type);
		}
		List<Map> list = (List<Map>)QBuilder.db("basedb").select(content).from("Health").where(where).query().getResultObj();
		if (list.size() == 0) {
			setErrcode(msg, NO_RESULT);
			return msg;
		}
		for (Map map : list) {
			List childList = QBuilder.db("basedb").select(content).from("Health").where(new Where("hospital=", hospital).and("status=", STATUS_ENABLE).and("parent=", Tools.getInt(map.get("id") + ""))).query().getResultObj();
			if (childList.size() > 0) {
				map.put("child", childList);
				map.put("have_child", "1");
			} else {
				map.put("have_child", "0");
			}
		}
		msg.put("health_list", list);
		return msg;
	}

	// 用户填写健康数据
	Message complete(Map<String, String> parameters) {
		Message msg = new Message(0);
		Date time = null;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			time = format.parse(parameters.get("time"));
		} catch (Exception e) {
			setErrcode(msg, ARGUMENT_ILLEGAL);
			return msg;
		}
		String data = parameters.get("data");
		Integer hospital = Tools.getInt(parameters.get("hospital"));
		Integer uid = Tools.getInt(parameters.get("uid"));
		Integer hid = Tools.getInt(parameters.get("hid"));
		String unit = Tools.getDesc(parameters.get("unit"), "");
		String healthName = parameters.get("health_name");
		if (hospital == 1104 && "血糖".equals(healthName)) {
			QBuilder.db("basedb").execHQL("delete from HealthData where hospital = 1104 and uid = " + uid + " and DATE_FORMAT(time, '%Y-%m-%d %H:%i') = '" + parameters.get("time") + "' and data =" + data + " and hid = " + hid + " and unit = '" + unit + "' and status = 1");
		}
		String key = parameters.get("key");
		List<Health> healthList = QBuilder.db("basedb").select().from("Health").where(new Where("hospital=", hospital).and("status=", STATUS_ENABLE).and("id=", hid)).query().getResultObj();
		if (healthList.size() > 0) {
			Health health = healthList.get(0);
			String defaultUnit = health.getDefaultUnit();
			HealthData healthData = new HealthData();
			if (health.getDefaultUnit() == null && (unit == null || "".equals(unit))) {
				healthData.setResult(data);
			} else {
				Double dobDate = Tools.getDouble(data);
				if (dobDate != null) {
					if (!unit.equals(defaultUnit)) {
						List<Map> unitList = (List<Map>)QBuilder.db("basedb").select("new map(rate as rate)").from("unit_conversion").where(new Where("original_unit=", unit).and("default_unit=", defaultUnit).and("health_name=", healthName)).query().getResultObj();
						Double rate = (unitList.size() == 0 ? 1 : (Double)unitList.get(0).get("rate"));
						dobDate = dobDate * rate;
					}
					if (health.getLowValue() == null && health.getHighValue() == null){
					} else if (health.getLowValue() != null && dobDate < health.getLowValue()) {
						healthData.setResult("偏低");
					} else if (health.getHighValue() != null && dobDate > health.getHighValue()) {
						healthData.setResult("偏高");
					} else {
						healthData.setResult("正常");
					}
				}
				healthData.setData(dobDate);
			}
			healthData.setTid(Tools.getInt(parameters.get("tid") + "", -9999));
			healthData.setTime(time);
			healthData.setUnit(defaultUnit);
			healthData.setJson("key", key);
			healthData.setHid(hid);
			healthData.setUid(uid);
			healthData.setHospital(hospital);
			DBTools.db("basedb").addItem(healthData);
			msg.put("result", healthData.getResult());
		}
		return msg;
	}

	// 根据时间搜索填写的健康数据
	Message list(Input input) {
		Message msg = new Message(0);
		Integer type = input.getInt("type");//日期类型 年1 月2 周3 日4 搜索5
		Integer uid = input.getInt("uid");
		Integer hid = input.getInt("hid");
		Integer hospital = input.getInt("hospital");
		String unit = input.getDesc("unit");
		String startTime = input.getDesc("start_time");
		String endTime = input.getDesc("end_time");
		String healthName = input.getDesc("health_name");
		List healthList = QBuilder.db("basedb").select("new map(id as id, name as name)").from("Health").where(new Where("parent=", hid).and("hospital=", hospital).and("status=", STATUS_ENABLE)).query().getResultObj();
		List result = new ArrayList();
		if (healthList.size() == 0) {
			Map healthMap = new HashMap();
			healthMap.put("id", hid + "");
			healthMap.put("name", healthName);
			healthList.add(healthMap);
		}
		for (int i = 0; i < healthList.size(); i++) {
			Map healthMap = (Map)healthList.get(i);
			hid = Tools.getInt(healthMap.get("id") + "", -9999);
			List list = QBuilder.db("basedb").select("defaultUnit").from("Health").where(new Where("id=", hid).and("hospital=", hospital).and("status=", STATUS_ENABLE)).query().getResultObj();
			Double rate = 1.0;
			if (list.size() > 0 && !((String)list.get(0)).equals(unit)) {
				List rateList = QBuilder.db("basedb").select("rate").from("unit_conversion").where(new Where("original_unit=", unit).and("default_unit=", (String)list.get(0)).and("health_name=", healthName)).query().getResultObj();
				rate = (rateList.size() == 0 ? rate : (Double)rateList.get(0));
			}
			String period = null;
			String where = null;
			boolean isStartTimeNull = "".equals(startTime) || "暂无".equals(startTime);
			boolean isEndTimeNull = "".equals(endTime) || "暂无".equals(endTime);
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			switch(type){
				case 1:
					format = new SimpleDateFormat("yyyy-MM");
					where = " and date_format(time, '%Y-%m') <= '" + (isStartTimeNull ? format.format(new Date()) : startTime) + "' and date_format(time, '%Y-%m') >= '" + (isStartTimeNull ? getRecentlyYearMonth(format.format(new Date())) : getRecentlyYearMonth(startTime)) + "'";
					period = "date_format(time, '%Y-%m')";
					break;
				case 2:
					format = new SimpleDateFormat("yyyy-MM-dd");
					where = " and date_format(time, '%Y-%m-%d') <= '" + (isStartTimeNull ? format.format(new Date()) : startTime) + "' and date_format(time, '%Y-%m-%d') >= '" + (isStartTimeNull ? getRecentlyMonthDay(format.format(new Date())) : getRecentlyMonthDay(startTime)) + "'";
					period = "date_format(time, '%Y-%m-%d')";
					break;
				case 3:
					where = " and date_format(time, '%Y-%m-%d') <= '" + (isStartTimeNull ? format.format(new Date()) : startTime) + "' and date_format(time, '%Y-%m-%d') >= '" + (isStartTimeNull ? getSixAgoDay(format.format(new Date())) : getSixAgoDay(startTime)) + "'";
					period = "date_format(time, '%Y-%m-%d')";
					break;
				case 4:
					where = " and date_format(time, '%Y-%m-%d') = '" + (isStartTimeNull ? format.format(new Date()) : startTime) + "'";
					period = "hour(time)";
					break;
				case 5:
					where = " and date_format(time, '%Y-%m-%d') <= '" + (isEndTimeNull ? format.format(new Date()) : endTime) + "' and date_format(time, '%Y-%m-%d') >= '" + (isStartTimeNull ? format.format(new Date()) : startTime) + "'";
					period = "date_format(time, '%Y-%m-%d')";
					break;
				default:
					break;
			}
			String hql = "select new map(concat(round(max(data)/" + rate + ", 2), '') as max_value, concat(round(min(data)/" + rate + ", 2), '') as min_value, concat(round(avg(data)/" + rate + ", 2), '') as avg_value, " + period + " as time) from HealthData where uid = " + uid + " and hid = " + hid + " and hospital = " + hospital + " and status = " + STATUS_ENABLE + where + " group by " + period + " order by time desc";
			List dataList =  QBuilder.db("basedb").queryHql(hql);
			if (dataList.size() == 0) {
				setErrcode(msg, NO_RESULT);
				return msg;
			}
			Map map = new HashMap();
			map.put("data_list", dataList);
			hql = "select new map(concat(round(max(data)/" + rate + ", 2), '') as max_value, concat(round(min(data)/" + rate + ", 2), '') as min_value, concat(round(avg(data)/" + rate + ", 2), '') as avg_value) from HealthData where uid = " + uid + " and hid = " + hid + " and hospital = " + hospital + " and status = " + STATUS_ENABLE + where;
			dataList =  QBuilder.db("basedb").queryHql(hql);
			map.putAll((Map)dataList.get(0));
			map.put("health_name", healthMap.get("name"));
			result.add(map);
		}
		msg.put("list", result);
		return msg;
	}

	// 查询所有填写的健康数据
	Message queryAll(Input input) {
		Message msg = new Message(0);
		Integer uid = input.getInt("uid");
		Integer hid = input.getInt("hid");
		Integer hospital = input.getInt("hospital");
		String unit = input.getDesc("unit");
		String healthName = input.getDesc("health_name");
		List list = QBuilder.db("basedb").select("defaultUnit").from("Health").where(new Where("id=", hid).and("hospital=", hospital).and("status=", STATUS_ENABLE)).query().getResultObj();
		Double rate = 1.0;
		if (list.size() > 0 && !((String)list.get(0)).equals(unit)) {
			List rateList = QBuilder.db("basedb").select("rate").from("unit_conversion").where(new Where("original_unit=", unit).and("default_unit=", (String)list.get(0)).and("health_name=", healthName)).query().getResultObj();
			rate = (rateList.size() == 0 ? rate : (Double)rateList.get(0));
		}
		if ("血压".equals(healthName)) {
			List healthList = QBuilder.db("basedb").select("id").from("Health").where(new Where("parent=", hid).and("hospital=", hospital).and("status=", STATUS_ENABLE)).query().getResultObj();
			String hql = "select new map(concat(round(data/" + rate + ", 2), '') as data, date_format(time, '%m月%d日 %H:%i') as time, jsonString as key, result as result) from HealthData h where uid = " + uid + " and hid = " + healthList.get(0) + " and hospital = " + hospital + " and status = " + STATUS_ENABLE + " order by h.time desc";
			List lowList = QBuilder.db("basedb").queryHql(hql);
			if (lowList.size() == 0) {
				setErrcode(msg, NO_RESULT);
				return msg;
			}
			hql = "select new map(concat(round(data/" + rate + ", 2), '') as data, date_format(time, '%m月%d日 %H:%i') as time, jsonString as key, result as result) from HealthData h where uid = " + uid + " and hid = " + healthList.get(1) + " and hospital = " + hospital + " and status = " + STATUS_ENABLE + " order by h.time desc";
			List highList = QBuilder.db("basedb").queryHql(hql);
			List result = new ArrayList();
			for (int i = 0; i < lowList.size(); i++) {
				Map lowMap = (Map)lowList.get(i);
				Map lowKeyMap = GsonUtil.fromJson(Tools.getDesc(lowMap.get("key"), ""), new TypeToken<Map>(){});
				for (int j = 0; j < highList.size(); j++) {
					Map highMap = (Map)highList.get(i);
					Map highKeyMap = GsonUtil.fromJson(Tools.getDesc(highMap.get("key"), ""), new TypeToken<Map>(){});
					if ((lowKeyMap.get("key") + "").equals(highKeyMap.get("key") + "")) {
						Map resultMap = new HashMap();
						resultMap.put("data", lowMap.get("data") + "/" + highMap.get("data"));
						resultMap.put("time", lowMap.get("time"));
						resultMap.put("result", getLastResult(lowMap.get("result"), highMap.get("result")));
						resultMap.put("id", lowKeyMap.get("key"));
						result.add(resultMap);
						break;
					}
				}
			}
			msg.put("data_list", result);
		} else {
			String hql = "select new map(concat(id, '') as id, concat(round(data/" + rate + ", 2), '') as data, date_format(time, '%m月%d日 %H:%i') as time, concat(cTime, '') as create_time, result as result) from HealthData h where uid = " + uid + " and hid = " + hid + " and hospital = " + hospital + " and status = " + STATUS_ENABLE + " order by h.time desc";
			List dataList = QBuilder.db("basedb").queryHql(hql);
			if (dataList.size() == 0) {
				setErrcode(msg, NO_RESULT);
				return msg;
			}
			msg.put("data_list", dataList);
		}
		return msg;
	}

	// 查询填写的健康数据详情
	Message detail(Input input) {
		Message msg = new Message(0);
		Integer hid = input.getInt("hid");
		String hdid = input.getDesc("hdid");
		Integer hospital = input.getInt("hospital");
		String unit = input.getDesc("unit");
		String healthName = input.getDesc("health_name");
		List list = QBuilder.db("basedb").select("defaultUnit").from("Health").where(new Where("id=", hid).and("hospital=", hospital).and("status=", STATUS_ENABLE)).query().getResultObj();
		Double rate = 1.0;
		if (list.size() > 0 && !((String)list.get(0)).equals(unit)) {
			List rateList = QBuilder.db("basedb").select("rate").from("unit_conversion").where(new Where("original_unit=", unit).and("default_unit=", (String)list.get(0)).and("health_name=", healthName)).query().getResultObj();
			rate = (rateList.size() == 0 ? rate : (Double)rateList.get(0));
		}
		if ("血压".equals(healthName)) {
			String hql = "select new map(concat(round(hd.data/" + rate + ", 2), '') as data, date_format(hd.time, '%Y年%m月%d日 %H:%i:%s') as time, h.name as name, hd.result as result) from Health h, HealthData hd where h.id = hd.hid and h.parent = " + hid + " and h.hospital = " + hospital + " and hd.hospital = " + hospital + " and hd.status = " + STATUS_ENABLE + " and h.status = " + STATUS_ENABLE + " and hd.jsonString like '%\"" + hdid + "\"%'";
			List dataList =  QBuilder.db("basedb").queryHql(hql);
			Map result = new HashMap();
			Object lowResult = null;
			Object highResult = null;
			for (int i = 0; i < dataList.size(); i++) {
				Map dataMap = (Map)dataList.get(i);
				if ("收缩压".equals(Tools.getDesc(dataMap.get("name"), ""))) {
					result.put("press_value", dataMap.get("data"));
					lowResult = dataMap.get("result");
				} else if ("舒张压".equals(Tools.getDesc(dataMap.get("name"), ""))){
					result.put("dias_value", dataMap.get("data"));
					highResult = dataMap.get("result");
				}
				result.put("time", dataMap.get("time"));
				result.put("name", healthName);
				result.put("create_time", DateUtil.formatDateByFormat(new Date(Tools.getLong(hdid)), "yyyy年MM月dd日 HH:mm:ss"));
			}
			result.put("result", getLastResult(lowResult, highResult));
			msg.put("health_data", result);
		} else {
			String hql = "select new map(concat(round(hd.data/" + rate + ", 2), '') as data, date_format(hd.time, '%Y年%m月%d日 %H:%i:%s') as time, hd.cTime as create_time, h.name as name, hd.result as result) from HealthData hd, Health h where hd.hid = " + hid + " and hd.hospital = " + hospital + " and h.hospital = " + hospital + " and h.status = " + STATUS_ENABLE + " and hd.status = " + STATUS_ENABLE + " and hd.hid = h.id and hd.id = " + hdid + " order by time desc";
			List dataList =  QBuilder.db("basedb").queryHql(hql);
			if (dataList.size() == 0) {
				setErrcode(msg, NO_RESULT);
				return msg;
			}
			Map map = (Map)dataList.get(0);
			map.put("create_time", DateUtil.formatDateByFormat(new Date(Tools.getLong(map.get("create_time") + "")), "yyyy年MM月dd日 HH:mm:ss"));
			msg.put("health_data", map);
		}
		return msg;
	}

	String getLastResult(Object lowResult, Object highResult) {
		String low = Tools.getDesc(lowResult);
		String high = Tools.getDesc(highResult);
		String result = null;
		if ("偏高".equals(low) || "偏高".equals(high)) {
			result = "偏高";
		} else if ("偏低".equals(low) || "偏低".equals(high)) {
			result = "偏低";
		} else {
			result = low;
		}
		return result;
	}

	String getRecentlyYearMonth(String date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		Date d = null;
		try{
			d = format.parse(date);
		}catch(Exception e){
		}
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.MONTH, -12);
		return format.format(c.getTime());
	}

	String getRecentlyMonthDay(String date) {
		Date d = DateUtil.parseDate(date);
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.DAY_OF_MONTH, -30);
		return DateUtil.formatDate(c.getTime());
	}

	String getSixAgoDay(String date){
		Date d = DateUtil.parseDate(date);
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.DAY_OF_MONTH, -6);
		return DateUtil.formatDate(c.getTime());
	}

%>
